package com.tidu.manager;

import com.tidu.entry.DataSourceMetadata;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class MetadataRepository {
    // 主数据源配置（存放元数据表的数据源）
    private static final String META_DB_URL = "jdbc:mysql://localhost:3306/source_db";
    private static final String META_DB_USER = "root";
    private static final String META_DB_PASSWORD = "1234";
    
    /**
     * 获取所有激活的数据源元数据
     */
    public List<DataSourceMetadata> getAllActiveMetadata() {
        List<DataSourceMetadata> metadataList = new ArrayList<>();
        String sql = "SELECT * FROM data_source_metadata WHERE is_active = true";
        
        try (Connection conn = DriverManager.getConnection(META_DB_URL, META_DB_USER, META_DB_PASSWORD);
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {
            
            while (rs.next()) {
                DataSourceMetadata metadata = new DataSourceMetadata();
                metadata.setId(rs.getInt("id"));
                metadata.setSourceName(rs.getString("source_name"));
                metadata.setDbType(rs.getString("db_type"));
                metadata.setJdbcUrl(rs.getString("jdbc_url"));
                metadata.setUsername(rs.getString("username"));
                metadata.setPassword(rs.getString("password"));
                metadata.setTableName(rs.getString("table_name"));
                metadata.setActive(rs.getBoolean("is_active"));
                metadata.setDescription(rs.getString("description"));
                metadata.setCreatedAt(rs.getTimestamp("created_at"));
                metadata.setUpdatedAt(rs.getTimestamp("updated_at"));
                
                metadataList.add(metadata);
            }
        } catch (SQLException e) {
            System.err.println("获取元数据失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return metadataList;
    }
}